text:
Q: I can`t do any action on new activity I am new to android. I would like to ask you some question.
When I calling new activity from main activity by commands
Intent myIntent = new Intent(v.getContext(), PolarView.class);
//startActivityForResult(myIntent, 0);
startActivityForResult(myIntent, 0);
finish();

then in new activity I can't do any actions, e.g. such as button click
Both
Button btnSeven = (Button) this.findViewById(R.id.btn7);
    btnSeven.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            InputStr = InputStr + "7";
        InputViewField.setText(InputStr);

        }
    });
}

and
public void btn7_click(View v) {
        InputStr = InputStr + "7";
        InputViewField.setText(InputStr);
}

having defined android:onClick="btn7_click" in activity`s layout
where InputViewField is EditText object
In the first case new activity does not start, in the second case when I press this button, aplication crashes.
could you please help me?
Here is some last peace of logcat after change
StartActivityForResult()

to
StartActivity()

Logcat:
D/MediaScanner(  153): opendir /system/media/ failed, errno: 2
D/MediaScanner(  153):  prescan time: 25225ms
D/MediaScanner(  153):     scan time: 162ms
D/MediaScanner(  153): postscan time: 48ms
D/dalvikvm(  109): GC freed 1920 objects / 95640 bytes in 160ms
D/MediaScanner(  153):    total time: 25435ms
D/MediaScannerService(  153): done scanning volume internal
D/MediaScannerService(  153): start scanning volume external
D/dalvikvm(   52): GREF has increased to 301
I/ActivityManager(   52): Starting activity: Intent { cmp=complex.ComplexCalc/.PolarView }
I/ActivityManager(   52): Displayed activity complex.ComplexCalc/.PolarView: 1414 ms (total 1414 ms)
V/MediaScanner(  153): pruneDeadThumbnailFiles... android.database.sqlite.SQLiteCursor@43bc30b8
V/MediaScanner(  153): /pruneDeadThumbnailFiles... android.database.sqlite.SQLiteCursor@43bc30b8
D/MediaScanner(  153):  prescan time: 1509ms
D/MediaScanner(  153):     scan time: 405ms
D/MediaScanner(  153): postscan time: 323ms
D/MediaScanner(  153):    total time: 2237ms
D/MediaScannerService(  153): done scanning volume external
D/AndroidRuntime(  223): Shutting down VM
W/dalvikvm(  223): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
E/AndroidRuntime(  223): Uncaught handler: thread main exiting due to uncaught exception
D/dalvikvm(  223): GC freed 3456 objects / 221888 bytes in 153ms
E/AndroidRuntime(  223): java.lang.IllegalStateException: Could not execute method of the activity
E/AndroidRuntime(  223):    at android.view.View$1.onClick(View.java:2031)
E/AndroidRuntime(  223):    at android.view.View.performClick(View.java:2364)
E/AndroidRuntime(  223):    at android.view.View.onTouchEvent(View.java:4179)
E/AndroidRuntime(  223):    at android.widget.TextView.onTouchEvent(TextView.java:6541)
E/AndroidRuntime(  223):    at android.view.View.dispatchTouchEvent(View.java:3709)
E/AndroidRuntime(  223):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
E/AndroidRuntime(  223):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
E/AndroidRuntime(  223):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
E/AndroidRuntime(  223):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
E/AndroidRuntime(  223):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
E/AndroidRuntime(  223):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
E/AndroidRuntime(  223):    at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
E/AndroidRuntime(  223):    at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
E/AndroidRuntime(  223):    at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
E/AndroidRuntime(  223):    at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
E/AndroidRuntime(  223):    at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
E/AndroidRuntime(  223):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(  223):    at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime(  223):    at android.app.ActivityThread.main(ActivityThread.java:4363)
E/AndroidRuntime(  223):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(  223):    at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime(  223):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
E/AndroidRuntime(  223):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
E/AndroidRuntime(  223):    at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(  223): Caused by: java.lang.reflect.InvocationTargetException
E/AndroidRuntime(  223):    at complex.ComplexCalc.PolarView.btn7_click(PolarView.java:266)
E/AndroidRuntime(  223):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(  223):    at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime(  223):    at android.view.View$1.onClick(View.java:2026)
E/AndroidRuntime(  223):    ... 23 more
E/AndroidRuntime(  223): Caused by: java.lang.NullPointerException
E/AndroidRuntime(  223):    ... 27 more
I/Process (   52): Sending signal. PID: 223 SIG: 3
I/dalvikvm(  223): threadid=7: reacting to signal 3
I/dalvikvm(  223): Wrote stack trace to '/data/anr/traces.txt'
I/ARMAssembler(   52): generated scanline__00000077:03515104_00000000_00000000 [ 33 ipp] (47 ins) at [0x46eae8:0x46eba4] in 1562593 ns
I/ARMAssembler(   52): generated scanline__00000177:03515104_00001001_00000000 [ 91 ipp] (114 ins) at [0x46eba8:0x46ed70] in 1903198 ns
I/Process (  223): Sending signal. PID: 223 SIG: 9
I/ActivityManager(   52): Process complex.ComplexCalc (pid 223) has died.
I/WindowManager(   52): WIN DEATH: Window{43cc3920 complex.ComplexCalc/complex.ComplexCalc.PolarView paused=false}
E/gralloc (   52): [unregister] handle 0x481778 still locked (state=40000001)
I/UsageStats(   52): Unexpected resume of com.android.launcher while already resumed in complex.ComplexCalc
W/InputManagerService(   52): Got RemoteException sending setActive(false) notification to pid 223 uid 10024

A: I think part of your problem is that you are using startActivityForResult(..), when in fact you should be using startActivity(..), because your new activity might not be returning anything.
However, without error logs its difficult to tell what is really happening


text:
Q: Android Navigation Drawer Activity call Click event from Fragment I created a Navigation Drawer Activity project in Android Studio and added some Fragments. Navigating through them works fine.
Now in the main fragment, I want to add some buttons that will take the user to some of the fragments, where the user would otherwise need to navigate to through the drawer menu. In other words, when the user opens the app, he should have the option to navigate to some fragments without opening the drawer menu. But I can't get it to work.
The closest I have come so far is with the following code in the main activity. However, this only works once. When I navigate to other fragments and go back to the main fragment, it will not work anymore. Clicking on the button should do the same as if the user navigated through the drawer menu.
public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.appBarMain.toolbar);
        binding.appBarMain.fab.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        DrawerLayout drawer = binding.drawerLayout;
        NavigationView navigationView = binding.navView;
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_hpfragment, R.id.nav_gallery, R.id.nav_slideshow)
                .setOpenableLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

        Button btnTest = binding.getRoot().findViewById(R.id.btnGotoDensityAlt);
        View.OnClickListener cl = new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                View x = navigationView.findViewById(R.id.nav_hpfragment);
                x.callOnClick();
            }
        };
        btnTest.setOnClickListener(cl);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }
}

What is the correct way to do this?

A: I solved this issue like this:
I added this function to the main activity:
public void navigateToHpCalc()
    {
        View view = binding.navView.findViewById(R.id.nav_hpfragment);
        view.callOnClick();
    }

I called this function in the fragment like this:
View.OnClickListener onGoToHpFragmentListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                MainActivity fa = (MainActivity)getActivity();
                fa.navigateToHpCalc();
            }
        };

Full code:
public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.appBarMain.toolbar);
        binding.appBarMain.fab.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        DrawerLayout drawer = binding.drawerLayout;
        NavigationView navigationView = binding.navView;
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_hpfragment, R.id.nav_gallery, R.id.nav_slideshow)
                .setOpenableLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

    }

    public void navigateToHpCalc()
    {
        View view = binding.navView.findViewById(R.id.nav_hpfragment);
        view.callOnClick();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }
}

and
public class HomeFragment extends Fragment {

    private FragmentHomeBinding binding;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        HomeViewModel homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        final TextView textView = binding.textHome;
        final Button btn = binding.btnGotoDensityAlt;

        homeViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);

        View.OnClickListener onGoToHpFragmentListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                MainActivity fa = (MainActivity)getActivity();
                fa.navigateToHpCalc();
            }
        };

        View.OnClickListener onGoToGallery = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Navigation.findNavController(root).navigate(R.id.action_nav_home_to_nav_gallery);
            }
        };
        binding.btnGotoDensityAlt.setOnClickListener(onGoToHpFragmentListener);
        binding.btnGoToGallery.setOnClickListener(onGoToGallery);

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}

I am stil not sure this is the best practice way to do it though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't extend abstract class that is from other package I'm building a library for javascript and typescript(for extends) with webpack and typescript. I want to make class extend other npm library's(that exports abstract class) abstract class, but when i run compiled code, it throws error.

Class extends value undefined is not a constructor or null

It seems that the program tries to load abstract class in compiled(js) class on runtime.
My codes:
webpack config
const development = process.env.dev === "true" ? true : false;

console.log(development);

const path = require("path");

module.exports = {
    mode: development ? "development" : "production",
    target: 'node',
    entry:{
        index:"./src/index.ts"
    },
    output:{
        libraryTarget: 'commonjs2',
        filename: 'index.js',
        path: path.resolve(__dirname, "dist")
    },
    module: {
      rules: [
        {
          test: /\.tsx?$/,
          use: 'ts-loader',
          //exclude: /node_modules/,
        },
      ]
    },
    resolve: {
      extensions: ['.ts', '.js', '.json']
    },
    plugins: [
    ],
    externals: [

    ]
};

tsconfig
{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es2017",
        "esModuleInterop": true,
        "declaration": true,
        "baseUrl": ".",
        "paths": {
            "@src/*":["src/*"]
        },
        "lib": ["dom","es2017"]
    },
    "include": [
        "src/*",
        "src/**/*"
    ]
}

Compiler.ts
import { Controller } from "npmLibraryName"; //Controller is abstract class

class Compiler extends Controller {
    init(){}
}

export default Compiler;


text:
Q: What's the solution to share information among the processors? I am writing a new algorithm for my finite analysis code using c++, suppose I am working on a 64*64 square mesh and it has four surfaces (surface A, B, C, D), and then I decompose it into four sub-domains, and it happens that the surface cells in surface A MAY also be scattered.
My question is kind of general, I am wondering if I want to calculate a variable in this 64*64 grids, but this variable depends on the entire surface A's coordinate information, then what should I do? Because I found that in some sub-domains, there is no A at all. So I found my code and new algorithm runs very well and successfully in serial, but it fails immediately in parallel.
Any advice or strategies for handling this kind of situation?

A: Parallel processing may be tricky, if you are using a algorithm based on shared memory paradigm you need to protect this memory region or you will have a race condition.
Other paradigms, like distributed memory, have other kind of strategies to handle this, mostly message passing.


text:
Q: Collection Fantasy story book When I was little (late 80s early 90s) my mom got me this book. I don't remember what it actually was about. It was for sure above my level at 5 or 6. I'm not even sure if she ever read it to me. It was hard cover and the book was silvery grey. No pictures on the cover. There was no dust jacket.
I do clearly and vividly remember the pictures. They were of wizards male and female. Their dragons and their castles. I also think there was a wizard for each season. They were BEAUTIFUL! I used to spend hours looking at it.
Each chapter was a different wizard, Dragon and castle. There was one for each season I think. I am pretty sure it started in spring or winter. Something is making me think the spring wizard was called the vernal wizard or something similar

A: This may be the Dragonlance chronicles by Margaret Weis and Tracy Hickman.
Note: I'm assuming you haven't read the series but are mostly remembering the covers.

*

*The timing is right.

*The hardcover dustcover is white, so I'm assuming the cover itself could be silvery grey.

*The pictures were done by Larry Elmore and are certainly captivating. He did a lot of work for D&D in general and Dragonlance in particular.

*There were three novels with three seasons: autumn, winter and spring.

*

*Each cover had a dragon and one or more of the characters.

*autumn had a female cleric with a magic staff and a red dragon.

*winter had a female elf with a dragonlance, which kinda looks like a staff and a blue dragon.

*spring had a red mage and staff and a green dragon.

Here are the the covers:

On the other hand, there were no combination wizards, dragons and castles, though dragonlords were paired with dragons.


text:
Q: PHP DOM return as html I have an xml file slider.xml with html code inside:
<?xml version="1.0" encoding="UTF-8"?>
<content>
    <title>Slider</title>
    <head>
        <script async="async" src='ws-custom/plugins/slider.js'></script>
        <script async="defer" src='ws-custom/plugins/functions.js'></script>
    </head>
    <footer>
        <script async="defer" src='ws-custom/plugins/jquery.js'></script>
    </footer>
</content>

In PHP I would like to:
1. load it (using simplexml, dom or other better solution) and store in a variable $xml;
2. create an array $head with both $xml->head->children();
3. return the original html code for $head[0] and $head[1].
I have tried using this code:
$xml = simplexml_load_file('slider.xml');
$head = $xml->head->children();
foreach($head as $element){
    echo $element->asXML();
}

but it returns self-closing tags:
<script async="async" src="ws-custom/plugins/slider.js"/>
<script async="defer" src="ws-custom/plugins/functions.js"/>

which is not valid html code for W3C http://validator.w3.org/nu/
I would like also to be able to write only async, i.e.

because it's valid html, but with simplexml it's not valid xml.
Thank you very much.
Best regards.

A: I've edited the script, now it works perfectly.
Note please the row 6:
$element[] = null;
<?php
$xml = new DOMDocument();
$xml = simplexml_load_file('slider.xml');
$head = $xml->head->children();
foreach($head as $element){
    $element[] = null;
    echo $element->asXML().PHP_EOL;
}

A: SimpleXML can't output the empty tags properly, you should use DOMDocument instead (LIBXML_NOEMPTYTAG doesn't work in SimpleXML)...
$xml = new DOMDocument('1.0');
$xml->load("slider.xml");
$head = $xml->getElementsByTagName("head");
$headScripts= $head[0]->getElementsByTagName("script");
foreach($headScripts as $element){
    echo $xml->saveXML($element, LIBXML_NOEMPTYTAG).PHP_EOL;
}

This code gets a start point (the <head> tag), as you only want the first one it uses [0] and finds the <script> tags inside the start point.
Which with the test source gives...
<script async="async" src="ws-custom/plugins/slider.js"></script>
<script async="defer" src="ws-custom/plugins/functions.js"></script>


text:
Q: how to select many different data"s" from two table? I have two tables tableA, tableB
Two of them have col "ip",like this...

tableA-ip
1.1.1.1
1.1.1.2
1.1.1.3
1.1.1.4
1.1.1.5
1.1.1.6
1.1.1.7
1.1.1.8

tableB-ip
1.1.1.3
1.1.1.4
1.1.1.5
And what I want is
1.1.1.1
1.1.1.2
1.1.1.6
1.1.1.7
1.1.1.8
How to select it?

A: It looks like you want the set difference (that is, IPs in A that are not also in B), soooooo:
SELECT a.ip FROM tableA a WHERE tableA.ip NOT IN (SELECT b.ip FROM tableB)

A: Use NOT IN:
SELECT ip FROM TableA WHERE TableA.ip NOT IN (SELECT ip FROM TableB)

A: You can combine two result sets with UNION.
select ip from tableA
union
select ip from tableB;

http://dev.mysql.com/doc/refman/5.0/en/union.html
The default behavior is to remove duplicate rows.
If you want duplicate rows use UNION ALL.

A: select a.id from a minus select b.id from b

or
select a.id from a where a.id not in (select b.id from b)

A: SELECT col1, col2, .. , Ip from TableA
UNION
SELECT col, col2, ...., Ip from TableB

To get the differences you can use the MINUS Operator instead of UNION


text:
Q: Are all types extending std::is_floating_point required to implement FENV in C++11 standard? I'm implementing a function as follows:
template <typename FP>
void do_something(FP f){
    static_assert(std::is_floating_point<FP>::value, "not a floating point");
    ...
}

In this context, any floating point can be used (native or custom, i.e. multi-precision float libraries).
I wonder if standard states anything about what to expect from types overloading the is_floating_point. Can I count for them being required to work with FENV?
Can I assume the following code should work properly if a custom floating point implementation is overloading the std::is_floating_point?
template <typename FP>
void do_something(FP f){
    static_assert(std::is_floating_point<FP>::value, "not a floating point");
    if (std::fetestexcept(FE_DIVBYZERO)){
        ...
    }
}

A: There ain't no such thing as a "custom floating point type", as far as std::is_floating_point is concerned.

20.10.4.1/1 The primary type categories correspond to the descriptions given in section 3.9 of the C++ standard.
Table 47 — Primary type category predicates
template <class T> struct is_floating_point; T is a floating point type (3.9.1)
3.9.1/8 There are three floating point types: float, double, and long double.
17.6.4.2.1/1 The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.


text:
Q: Error while downloading google APIs Intel x86 atom system image I just started to work with Android Studio and I stuck with one problem .
When I try to download a system image and create an AVD I get this error

" Install Google APIs Intel x86 Atom System Image (revision: 9) failed

and no matter what API level and what release I try to download, I get this error anyway ...
 any solutions ??
This is a screenshot of the error

A: Defining the problem
I faced the same problem while installing Android SDK on Windows OS:

Install Google APIs Intel x86 Atom System Image (revision: 9) failed

I went through the blogs to fix the problem. The problem is that the following subfolder is not created: %LocalAppData%\Android\Sdk\system-images\android-30\google_apis\x86
NOTE: The name of the android-30 folder changes according to the API level.
This issue is caused by Android Studio running without administrative privileges during installation. So don't try to install Android SDK after installing Android Studio; close Android Studio and run it again with administrative privileges. Follow the steps below to fix the problem:
Step-1
Run Android Studio with admin privileges:

Step-2
To install Android SDK, open Android Studio and follow these steps:

*

*File > Settings > Appearance & Behavior > System Settings > Android SDK

*Select the desired SDK and wait for the installation to complete.

A: 1- Do not close the installer
2- Click on "show details"
3- Inside the installer it gives for you this link: https://dl.google.com/android/repository/sys-img/google_apis/x86-30_r09.zip
4- Access it and make the download manually
5- Go to
---Your main root (C: for example) -> Users -> Your main user -> Enable "show oculted files" -> AppData -> Local -> Android -> Sdk
6- Search for google_apis (at the search bar)
7- Open the x86-30_r09.zip and copy the files inside x86 folder
8- At google_apis enter at x86 folder and paste the files
9- Click "Retry" on the installer's error message.
If it stop again with the other download, you can do the same steps but using the another link for x86-2 file

A: Go to SDK manager and then search Optimize Disk Space on top right.
Use Optimize Disk Space to clean the error stored part of INTEL ATOM SYSTEM IMAGE. Now, Update or download it again.

A: Use the Android SDK bundled with Android Studio.
In Preferences > Appearance and Behavior > System Settings > Android SDK
Edit the Android SDK path:
For Windows:
C:\Users\<user>\AppData\Local\Android\Sdk
For MacOS X:
/Users/<user>/Library/Android/sdk

A: Use the Android SDK bundled with Xamarin Visual Studio.

*

*Close the Andriod SDK

*Rebuild the Solution

*Clean the Solution

*Once again open the Andriod SDK in Visual Studio and then download

A: Ubuntu 20.04
Remove .downloadIntermediates/ folder from your SDK location /.../Android/Sdk/


text:
Q: Fitting ARIMA to time series with missing values I have a stationary time series object (e.g.: xts) consisting of weekly continuous data. Values are missing for several weeks, sometimes randomly but often in chunks of 4-5 weeks. I want to fit a time series model to the data for forecasting using the "arima" function.
Does the function "arima" take into account the missing weeks? Looks like it does not use the time index at all! Here's my code:
o.time.pos <- seq(1:(52*5))
z.idx <- seq.Date(as.Date("2010/1/1"), by="week", length.out = 52*5)
sigma <- 1.15
phi <- 0.8
y_ts <- arima.sim(n = length(o.time.pos), list(ar = c(phi)), sd = sigma)
y.ts <- xts(as.numeric(y_ts), order.by=z.idx)
y.ts.na <- y.ts
# Missing values as NAs
y.ts.na[c(40:45, 72:82)] <- NA
ar1 <- arima(y.ts.na, order=c(2,1,2), method="ML")
y.ts.na1 <- y.ts
# Missing values are deleted from the time series. However, the time
# index shows that there are weeks missing
y.ts.na1 <- y.ts.na1[-c(40:45, 72:82)]
y.ts.na1
2010-09-10 -0.341071731
2010-09-17 -2.141615586
2010-09-24 -1.538637593
2010-11-12 -2.801102613
2010-11-19 -2.447482778
2010-11-26 -3.176720246
2010-12-03 -2.532530896
ar2 <- arima(y.ts.na1, order=c(2,1,2), method="ML")

I expect ar1 and ar2 to be same but they are not.
summary(ar1)

Call:
arima(x = y.ts.na, order = c(2, 1, 2), method = "ML")

Coefficients:
         ar1     ar2      ma1      ma2
      0.4367  0.1801  -0.6410  -0.3319
summary(ar2)

Call:
arima(x = y.ts.na1, order = c(2, 1, 2), method = "ML")

Coefficients:
         ar1     ar2      ma1      ma2
      0.5302  0.1231  -0.7473  -0.2298

It seems in the second method, even though the xts object has information on the missing weeks, the "arima" method does not seem to use this and instead treat the time as contiguous. In the above example, it seems to treat the data for 2010-11-12 as the data for the week after 2010-09-24 and so on. This is clearly wrong. I understand that putting together the likelihood with missing data is not possible. What are my options to fit a time series model to data with missing data?
I know one method is to impute the data (using, for example, How to use auto.arima to impute missing values  or How do I handle nonexistent or missing data?) and then fit but is it possible to fit without imputation?

A: The results given by stats::arima in the first approach (ar1) are correct: they have taken into account the missing values. In the second one, they have not.
You can fit ARIMA models with missing values easily because all ARIMA models are state space models and the Kalman filter, which is used to fit state space models, deals with missing values exactly by simply skipping the update phase.  So, "putting together the likelihood with missing data" is absolutely possible, as is done by the Kalman filter. Any other state space model will allow you to do the same.
Unless you are specifically interested in an estimate of those missing values, you do not need to impute them. If you do so incorrectly, you could distort the dynamics, which would cause problems when trying to fit your model afterwards. If you only want to forecast the series, you should probably not impute them.
The question of why ar1 is correct but not ar2 is not exactly on topic here, but for the record: stats::arima expects your data as an object of class ts, not xts. If your data isn't ts, it will be converted by using as.ts, which discards the date information; this means that the explicit NA's in the first approach are retained, while the implicit ones in the second will not appear at all and it will indeed just glue the series together. The reason why stats::arima expects an object of class ts is because that class enforces regularly sampled data (at a certain frequency), whereas xts can carry arbitrarily sampled data, and classical ARIMA models are defined for regularly sampled data only.


text:
Q: How do I copy program files from Windows partition to my Ubuntu partition I am dual-booting Windows 7 and Ubuntu 12.04 and I play World of Warcraft on my Windows OS.  I've been thinking about running WoW in Ubuntu but I have no idea how to copy the game files from the window partition to the Ubuntu OS partition.
I've downloaded Wine for support of WoW in Ubuntu but I'm kinda stuck here.  So how do I copy WoW in the wine directory?

A: For the purpose you want, you actually do not need to copy the files over. you can run WOW from within the windows partition. What you really have to do is the following to have everything working as it should:

*

*Install the PPA for WINE. You HAVE TO install the PPA which is much better. More info here: How to update Wine to the latest version?

*Install using winetricks (After having installed Wine) all DirectX 9 components. Since the release of Wine 1.4, you can just install the DirectX that comes with any Windows CD/DVD (eg: The DirectX 10 that comes with Skyrim). That should be enough to get DirectX working.

*Install the latest drivers for Intel, Nvidia or Ati. All of which you can find/install with this PPA: How do I install the latest Nvidia drivers via the Additional Drivers tool?

*Follow this link with any additional relevant information about WoW: http://appdb.winehq.org/objectManager.php?sClass=version&iId=25610

*Create a desktop shortcut/launcher as mentioned in this question to have a working one click icon: How can I edit/create new launcher items in Unity by hand? (Easy way here: https://askubuntu.com/a/128284/7035 )

*Edit the Desktop shortcut and in the command line type: wine "DIR" -opengl where DIR is the complete location of your Wow.exe file. For example in my case wine "/media/fun/games/World of Warcraft/Wow.exe" -opengl". The OpenGL is to give you more available graphics options. You can also remove it but for most video cards it is better to have it there to make the game run smoother.
If you still want to copy the Wow folder, you can put it on your Ubuntu home folder and do the same steps mentioned before. Just wanted to point out that you can run the game from the same Windows partition, does saving you space and time.

A: Quoting from Wine's FAQ:
Short answer: you have to install them in Wine just like you did in Windows. Applications usually have a setup or installer program.
http://wiki.winehq.org/FAQ#head-35dc1c1d64fb6da2753ff03a1dea1d261f240d11
The above link has detailed instructions on how to install Windows' applications in Wine.


text:
Q: Protrusion when draw an angle from two lines I'm learning how to draw with tikz and trying to draw an angle. I know how to draw an arc with \draw (0,0) circle (start, end, radius); but with an arbitrary angle from two lines, this is too complicated (require many calculations). So I went for an easier way in this question. My problem is the arc now protrudes out from its sides. How can I fix this? Also, is there any other simple way to draw an arc from two lines.
Here is my code. I hope it isn't too messy.
\documentclass[a4paper]{article}
\usepackage[top=1cm, bottom=1cm, left=2cm, right=1cm]{geometry}
\usepackage{tikz,calc}
\usetikzlibrary{angles}

\begin{document}
    \begin{tikzpicture}
    \draw [help lines] (0,0) grid (6,3);
    \draw[thick] (0,0)--(1.5,2)--(6,2)--(4.5,0)--cycle;
    \draw[thick,->] (2,1)node[left](A){A}--(4,0.5)node[right](B){B};
    \draw[thick,->] (2,1)--(3.5,1.5)node[right](C){C};

    %angle
    \pic [draw, angle radius=6mm, angle eccentricity=1.5] {angle = B--A--C};
    \end{tikzpicture}
\end{document}

A: You have to define the angle with coordinates and not with nodes. Coordinates are just points, while nodes have some size which is considered drawing the arc.
\documentclass[a4paper]{article}
\usepackage[top=1cm, bottom=1cm, left=2cm, right=1cm]{geometry}
\usepackage{tikz,calc}
\usetikzlibrary{angles}

\begin{document}
    \begin{tikzpicture}
    \draw [help lines] (0,0) grid (6,3);
    \draw[thick] (0,0)--(1.5,2)--(6,2)--(4.5,0)--cycle;
    \draw[thick,->] (2,1) coordinate[label=left:A] (A) --(4,0.5) coordinate[label=right:B] (B);
    \draw[thick,->] (2,1)--(3.5,1.5) coordinate[label=right:C](C);

    %angle
    \pic [draw, angle radius=6mm, angle eccentricity=1.5] {angle = B--A--C};
    \end{tikzpicture}
\end{document}


text:
Q: Python use def() to open and read file and write it in new format into new file I try to open and change the file. The code works only on first three line then its stack.
My file is:
Eskil Johnsson
7901105838
Löberöd 29, 521 29  KÄTTLISTORP
Anna Göransson
7102022980
Klubbvägen 18, 770 65  BY KYRKBY

My code:
def main():
    file_content = read_from_file()
    write_to_file(file_content)

def read_from_file():
    with open('C:\\Users\\saran\\OneDrive\\Dokument\\names2.txt', 'r+', encoding = 'utf_8') as f:
        file_content = []
        line = f.readline()
        line = line.split()
        while(len(line) > 0):
            print(line[1] + ' ' + line[0])
            line = f.readline()
            tal = int(line[8])
            if (tal % 2) == 0:
                print('[K]')
            else:
                print('[M]')
            line = f.readline()
            print(line)
        return file_content

main()

A: You aren't reading the lines in the while statement.
Try this:
    while(len(line) > 0):
        print(line[1] + ' ' + line[0])
        line = f.readline()
        tal = int(line[8])
        if (tal % 2) == 0:
            print('[K]')
        else:
            print('[M]')
        line = f.readline()
        print(line)
        line = f.readline()
        line = line.split()


text:
Q: Adding nil to NSMutableArray I am trying to create a NSMutableArray by reading in a .txt file and am having trouble setting the last element of the array to nil.
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"namelist" ofType:@"txt"];
NSString *data = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSArray *list = [data componentsSeparatedByString:@"\n"];
NSMutableArray *mutableList = [[NSMutableArray alloc] initWithArray:list];

I wanted to use NSMutableArray's function addObject, but that will not allow me to add nil. I also tried:
[mutableList addObject:[NSNull null]];

but that does not seem to work either. Is there a way around this problem?

A: Per Apple's documentation on NSMutableArray.
addObject:

Inserts a given object at the end of the receiver.

- (void)addObject:(id)anObject
Parameters

anObject

    The object to add to the end of the receiver's content. **This value must not be nil.**

Reference
http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html

A: Use
NSMutableArray *mutableList = [[NSMutableArray alloc] init];
[mutableList addObjectsFromArray:list];

Hope this helps
jrtc27


text:
Q: Why am I getting an uninitialized constant error when the model file exists? I'm getting the following error in pry after creating the model. I think I have all the pieces in place so cant be sure why. I haven't created the controller yet but I think I should still be able to access my model in pry before setting up the model.
NameError: uninitialized constant Deal

app/models/deal.rb
class Deal < ApplicationRecord
end

db/schema.rb

  create_table "deals", force: :cascade do |t|
    t.string "origin_city"
    t.string "destination_city"
    t.date "fly_out"
    t.date "check_in"
    t.date "check_out"
    t.date "trip_end"
    t.float "flight_price"
    t.float "hotel_price"
    t.date "date"
    t.integer "number_nights"
    t.string "hotel_link"
    t.string "search_results_link"
    t.string "flight_link"
    t.string "region"
    t.string "country"
  end

A: The code is correct. The problem was in opening pry and not the rails console to check the model connection.
bundle exec rails c

Using the above and going into pry via the console vs. just opening it works.


text:
Q: É seguro usar o novo açúcar sintático para callbacks em Javascript? Esses dias eu estava testando algumas funcionalidades do Javascript no Google Chrome 50 e percebi que já foi adicionada a arrow function para callbacks.
Assim:
$.each([1, 2, 3], x => x * 2);

// [2, 4, 6]

Antigamente teria que fazer assim:
$.each([1, 2, 3], function (x) { return x * 2; })

Já podemos usar essa opção seguramente para todos os navegadores (estamos em 2016!), ou ainda terei que esperar mais um pouquinho?

A: Não é seguro. O ECMAScript 6 não está recebendo suporte 100% das features ainda nos navegadores (mesmo os modernos), e mesmo que a última versão do navegador suporte essas features você ira limitar o funcionamento do seu site para esses navegadores. O ideal é programar com features do ECMAScript 5, eu sou adepto nessa ideia, apesar que tem gente que usa outras técnicas para que o código rode até com ECMAScript 3. Tudo depende do seu público, geralmente o suporte para o ECMAScript 5 é o essencial.
Você pode acompanhar o suporte dos navegadores e demais aqui:
http://kangax.github.io/compat-table/es6/
E caso queira mesmo assim usar ECMAScript 6, procure por outras alternativas como Babel, Traceur, Webpack...
Nesse projeto pessoal de um amigo eu fiz recentemente uma branch onde eu rejuvenesci todo o código para ES6. Uso Webpack com Babel nesse projeto e ele funciona em browsers antigos porque o código é transpilado para ES5.
https://github.com/pedrolaxe/js-terminal


text:
Q: change the submit method of a jquery POST form i have 2 jquery codes. How can i put this toghether.
example
if checkbox is checked use
<script>

$(document).ready(LoadMe);
 function LoadMe()
{
$('#msg_text').bind('keypress', function(e){
   var code = e.keyCode ? e.keyCode : e.which;
   if(code == 13 && !e.shiftKey) // Enter key is pressed
   {
     var msg = $("#msg_text").val();
var ontvanger = $("#ontvanger").val();
if ( $.trim( $('#msg_text').val() ) == '')
{

}
else
{
 $("#send_msg").hide();
 $("#dis_sub").show();
$.ajax({
type: "POST",
   url: "post_message.php",
data: { msg: msg, ontvanger: ontvanger},
cache: false,
success: function(html){

$("#msg_text").val('');
$("#content").prepend(html);
$("#dis_sub").hide();
$("#send_msg").show();
}
});
 }return false;
   }
});

}

else use
<script type="text/javascript">
$(function() {
$("#send_msg").click(function()
{
 var msg = $("#msg_text").val();
var ontvanger = $("#ontvanger").val();
if ( $.trim( $('#msg_text').val() ) == '')
{

}
else
{
$("#send_msg").hide();
$("#dis_sub").show();
$.ajax({
type: "POST",
url: "post_message.php",
data: { msg: msg, ontvanger: ontvanger},
cache: false,
success: function(html){

$("#msg_text").val('');
$("#content").prepend(html);
$("#dis_sub").hide();
$("#send_msg").show();
}
});
}return false;
}); });
</script>

if checkbox is checked i want to submit my form with a enter key else submit the form with click on a button

A: Put your submit code in a function say submit_form(). Then bind your events with this function. Check the checkbox status before submit.
$('#msg_text').bind('keypress', function(e){
   var code = e.keyCode ? e.keyCode : e.which;
   if(code == 13 && !e.shiftKey && checkbox.checked) submit_form();
});

$("#send_msg").click(function () {
    if (!checkbox.checked) submit_form();
});

A: function LoadMe(){

    $('#msg_text').bind('keypress', function(e){
       do keypress stuff . .  .
    }else{
       do normal submit stuff . . .
    }

}

Which will run the 'keypress' code if the key is pressed, otherwise it will run the 'other' code.

A: Add if condition to check whether check box is checked or not. you can use jQuery is() function with proper selection eg: is('#id_of_the_chekbox:cheked'), use css pseudo selector :checked then call your functions in true and false conditions.


text:
Q: Is it possible to save Dynamic Tables in SQL server? I'm working on a school project where I need to make a dynamic table in JavaFX, which should be saved in my SQL database.
The user should be able to specify the number of rows and columns needed.
Is it possible to save a dynamic table in SQL?
I've thought about exporting the dynamic table to a CSV file, and then save the information in the CSV file as a string. Then when you load the table again, a method would be needed to convert from string to table again. Seems like a stupid and inefficient way to do it though.
I've read some places that I should use XML or JSON in some way, but I never understood how.


text:
Q: Identity Server 4 how to map list of role into MVC application In Identity Server 4, I create role claim "Admin" for a user :
userMgr.AddClaimsAsync(user,
new Claim[]{ new Claim("role", "Admin") })

In client application I map this role and it works fine for only one role:
options.Scope.Add(RSIdentityServerConstants.Roles);
options.ClaimActions.MapJsonKey("role", "role", "role");
options.TokenValidationParameters.NameClaimType = "name";
options.TokenValidationParameters.RoleClaimType = "role";

[Authorize(Roles = "Admin")]  => Works fine
public IActionResult Index()
{
  return View();
}

But I need to map a list of role but I don't know How to create the claim and map to the asp net core mvc application?
[Authorize(Roles = "Admin, SuperAdmin, Others")]  => How to do ??
public IActionResult Index()
{
  return View();
}

userMgr.AddClaimsAsync(user,
new Claim[]{ new Claim("role", "Admin, SuperAdmin, Others") })  => this doesn't work

A: Just add the Claim in an array fashion:
new Claim[]{ new Claim("role", "Admin"), new Claim("role", "SuperAdmin"), ...  })


text:
Q: A question about metrizability In a lecture in Topology I had earlier this week, I was told (without proof) that not every topological space $(X,O)$ is metrizable, i.e, it is impossible to find some metric $d$ such that  $O$  and $O(d)$ are topologically equivalent. I've been trying to come up with a counter example but it's a bit hard to visualize. Does anyone know a reference or have a proof of this theorem?

A: There are certain topological properties that all metric spaces share:

*

*They are all Hausdorff (distinct points can be separated by disjoint open sets) and perfectly normal (normal means disjoint closed sets can be separated by disjoint open sets while the "perfectly" modifier means that additionally all closed sets are Gδ).

*The are all first-countable (each point has a basis of neighbourhoods consisting of only countably many sets).

*They are all paracompact (for any open cover $\mathcal{U}$ you can find another open cover $\mathcal{V}$ with the property that every set in $\mathcal{V}$ is a subset of some set in $\mathcal{U}$, and every point has a neighbourhood which meets only finitely many members of $\mathcal{V}$).

*If a metric space satisfies one of the following properties, it satisfies all of them:

*

*Separability (there is a countable dense set).

*Second-countability (there is a countable base).

*Lindelöfness (every open cover has a countable subcover).

*ccc-ness (every collection of pairwise disjoint open sets is countable).

(There is an analogous property for any infinite cardinal $\kappa$.)

*If a metric space satisfies one of the following properties, it satisfies all of them:

*

*Compactness (every open cover has a finite subcover).

*Countable compactness (every countable open cover has a finite subcover).

*Sequential compactness (every sequence has a convergent subsequence).

The above is not a complete list, but any space disobeying at least one of the above is not a metric space.
For example, the long line has the following properties which show it is not metrizable:

*

*it is a normal Hausdorff space which is not perfectly normal.

*it is sequentially compact and countably compact but not compact (or even Lindelöf).

*it is not paracompact.

A: Here is a good example I keep in mind.  There are minor things to check, but I like working with the familiar object $\mathbb{R}$.
Consider $\mathbb{R}$ with two different topologies: the "normal" topology on $\mathbb{R}$ (basis is given by open intervals $(a,b)$).  $\mathbb{R}$ with this topology is metrizable of course ($d(x,y) = |x-y|$).
Now, let's endow $\mathbb{R}$ with a different topology (called the lower limit topology) where the basis for open sets in $\mathbb{R}$ are given by intervals of the form $[a,b)$ (you should check that this is actually a basis).  Let's denote $\mathbb{R}$ with this topology as $\mathbb{R}_\ell$.
The two topologies $\mathbb{R}$ (standard one) and $\mathbb{R}_\ell$ looks similar, but you should convince yourself that $\mathbb{R}_\ell$ many many more open sets.  In fact, here is the crucial observation you should make: $\mathbb{R}$ with standard topology admits a countable basis (take all open intervals of rational radius centered at rational points), but $\mathbb{R}_\ell$ does not (you should prove, or at least convince yourself of this).
Now, a metric space with countable dense subset always admits a countable basis (like $\mathbb{R}$ with standard topology as we just discussed).  However, $\mathbb{R}_\ell$ has a countable dense subset but does not admit a countable basis, hence it must not be metrizable.
References: Munkres' Topology, my past topology class notes.

A: Every compact metrizable space is second-countable.  But the ordered square $[0,1]^2$ with the order topology induced  by the dictionary order is compact since it is a closed interval in its order.  However, it is not second countable, and therefore is not metrizable.

A: Let $X = \{a,b,c\}$ and let $\tau = \{\emptyset,X\}$ be a topology on $X$ (this is called the trivial topology on $X$). Then suppose (for a contradiction) that $(X,\tau)$ is metrizable, and let $d:X \to [0,\infty)$ be a metric on $X$ such that its metric topology coincides with $\tau$.
Then $U = \{x \in X : d(x,a) < d(a,b)\}$ is an open set. Note $b \not\in U$,
but $a \in U$, so we either have $U = \{a,c\}$ or $U = \{a\}$, neither of which are in $\tau$, and hence are not open, a contradiction.


text:
Q: Check overall UIColor? Is there a simple way to check the overall color of a UIImage?
//For example
if ([someImage isMostly:[[UIColor whiteColor] CGColor]] {
    NSLog(@"This image is mostly white!");
}

I would imagine it's not that simple though. One approach could be possibly to pick a few random coordinates and average the colors together. Am I on the right track?

A: One approach is to create the image histogram and then simply pick the most frequent color.


text:
Q: Getting the class of the components of an array If I have
public <T> doSomething(T[] array)
{
}

how can I get T.class from array?
If I do array.getClass() that gets me T[].class instead.

A: Component Type
Use this:
array.getClass().getComponentType()

Returns the Class representing the
  component type of an array. If this
  class does not represent an array
  class this method returns null.

Reference:

*

*Class.getComponentType()

Safe / Unsafe casting

Is there a way I can cast to Class
  from Class returned by
  getComponentType() without getting a
  compiler warning?

take this method:
public <T> void doSomething(final T[] array) throws Exception{
    final Class<? extends Object[]> arrayClass = array.getClass();
    final Class<?> componentType = arrayClass.getComponentType();
    final T newInstance = (T) componentType.newInstance();
}

Here's the generated byte code:
public void doSomething(java.lang.Object[] array) throws java.lang.Exception;
     0  aload_1 [array]
     1  invokevirtual java.lang.Object.getClass() : java.lang.Class [21]
     4  astore_2 [arrayClass]
     5  aload_2 [arrayClass]
     6  invokevirtual java.lang.Class.getComponentType() : java.lang.Class [25]
     9  astore_3 [componentType]
    10  aload_3 [componentType]
    11  invokevirtual java.lang.Class.newInstance() : java.lang.Object [30]
    14  astore 4 [newInstance]
    16  return

As you can see, the parameter type is erased to Object[], so the compiler has no way to know what T is. Yes, the compiler could use array.getClass().getComponentType(), but that would sometimes fail miserably because you can do stuff like this:
Object[] arr = new String[] { "a", "b", "c" };
Integer[] integerArray = (Integer[]) arr;
doSomething(integerArray);

(In this case array.getClass().getComponentType() returns String.class, but T stands for Integer. Yes, this is legal and does not generate compiler warnings.)

A: If you want to do this for multi-dimensional arrays the following recursive code will work
public static Class<?> getArrayType(Object array) {
    Object element = Array.get(array, 0);
    if (element.getClass().isArray()) {
        return getArrayType(element);
    } else {
        return array.getClass().getComponentType();
    }
}

A: Maybe an old thread, but I would like to share a tested version I did with all your recomendations:
    @NotNull
    @SafeVarargs
    public static <T> T coalesce(@NotNull T ... args) {
        for(T i : args) {
            if(i != null) {
                return i;
            }
        }
        T newInstance = null;
        try {
            final Class<? extends Object[]> arrayClass = args.getClass();
            final Class<?> componentType = arrayClass.getComponentType();
            newInstance = (T) componentType.newInstance();
        }catch(Exception e) {
            e.printStackTrace();
        }
        return newInstance;
    }

Hope will be usefull to you!
Best regards!


text:
Q: Dropbox Core API, notification if a file has been added to a folder I have an app that creates tickets by putting a file in a Dropbox folder. Based on this ticket a file is added to another (Dropbox) folder. I use the Dropbox Core API.
Now, I have to refresh the folder manually to see if the new file already has been added.
I am searching for a method to be notified when the folder is changed (a file has been added) but haven't found it. I guess longpoll_delta can do the job but that isn't available in the iOS API.
Is there a method to do this in Objective-c?
I retrieve the data the following way:
- (void) refreshTable {
    [self.restClient loadMetadata:@"path"];
}

- (void)restClient:(DBRestClient *)client loadedMetadata:(DBMetadata *)metadata {

    for (DBMetadata * child in metadata.contents) {
        if (!child.isDirectory && !child.isDeleted) {
            NSLog(@"Filename: %@", child.filename);
        }
    }
}

Any ideas?

A: The new Dropbox API v2 has function for this:
[[[dropboxClient.filesRoutes listFolderLongpoll:cursor] setResponseBlock:...];

Cursor parameter is returned by listFolder or listFolderContinue.


text:
Q: Zurb foundation framework - 100% height grid I'm using Zurb's foundation 12-column grid on my site and it's all built out and scaling well, unfortunately, I need the background of the site to be black and everything in the grid to be white. When I set the body to be black, the grid doesn't scale full-height so there is black underneath. Does anyone know of way to make the grid 100% height, either with CSS or JS?

A: you can try to use css with height 100% to main row or the container row and positioning them absolute.

A: Try setting:
  min-height: 100vh;
  max-height: 100vh;

e.g.

A

B

vh is viewport height and the viewport is the browser part that is visible for the website
Div A is going to always going to have the height of the viewport and if you resize the height of the browser the two divs are going to resize also.
I know my answer is late for the OP but I struggled with this problem and maybe I can help someone else.
Cheers


text:
Q: MySQL 4.0 Gibberish Cannot Convert to Newer MySQL One of the websites I host still runs on PHP 5.2 with MySQL 4.0. Its text is in Hebrew (displays just fine on the site), but in the DB the text appears as gibberish containing question marks—but not exclusively. It looks some like: ?????£ ?§???¥ ???£ ?×???
I am trying to move this DB to MySQL 5.x with the same website, with no luck so far. I have tried using the MYSQL 40 compatibility mode, as well as other compatibility modes. I have made sure that the destination DB has the hebrew_bin collation as the old one, and I've played around with SET NAMES. The problem is, this is a type of gibberish I am not yet familiar with and therefore have no idea how to convert it to readable text.

A: I didn't get another answer here, and therefore had no choice but to write a simple script that manually does the migration process through PHP and not through MySQL dumps.
Here is the script, with some obvious modifications. Please note that the script is "dirty code", it might not be secure and it's not the most efficient, but it should get the job done if you're using it internally. Do not use in an environment where the script is accessible to the public without further modifications.
<?php
    $local = mysqli_connect([source server], [source username], [source password], [source DB name]) or die('No local connection');
    mysqli_query($local, "SET NAMES 'hebrew'");

    $remote = mysqli_connect([destination server], [destination  username], [destination password], [destination DB name]) or die('No remote connection');
    mysqli_query($remote, "SET NAMES 'utf8'");

    $table_list = array('table1', 'table2', 'table3'); // you can get a list of tables automatically too if the list is very long

    foreach ($table_list as $table)
    {
        $query_local = "SELECT * FROM `{$table}`";

        $result_local = mysqli_query($local, $query_local) or die('Error in q1: '.mysqli_error($local));

        $delete_remote = mysqli_query($remote, "DELETE FROM `{$table}` WHERE 1") or die('Error deleting table: '.$table); // necessary only if you plan to run it more than once

        $i = 0;
        while ($row_local = mysqli_fetch_assoc($result_local))
        {
            foreach ($row_local as $key => $value)
                $row_local[$key] = mysqli_real_escape_string($remote, $value);

            $query_remote = "INSERT INTO `{$table}` (`".implode('`, `', array_keys($row_local))."`) VALUES ('".implode("', '", $row_local)."')";

            $result_remote = mysqli_query($remote, $query_remote)
                or die('Error in remote q'.$i.' in table '.$table.':
  '.mysqli_error($remote).'
  Query: '.$query_remote);

            echo 'Successfully transferred row '.$i.' in table '.$table;
            echo '
'.PHP_EOL;

            $i++;
        }
    }
?>


text:
Q: ios How do I know the controller is a "push" or "pop" returned i have three controller and i wanna kown the controller is a push or pop
A controller:
{
    if(!b)
     b = [B alloc] init];
    [self.navigationController pushViewController:b animated:YES];
}

B controller:
- (void) viewDidAppear:(BOOL)animated
{
     [super viewDidAppear:animated];
     //I want here to judge, from the "A" push over, or to return from the "C" "pop"

     //if it is push from A
     //dosomething.....

     //if it is pop from C
     //dosomething
}
-(void)testAction:(id)sender
{
    C *c = [[C alloc] init];
    [self.navigationController pushViewController:b animated:YES];
    [c release];
}

C controller:
{
    [self.navigationController popViewControllerAnimated:YES];
}

thanks.

A: Have a look at the UIViewController method, isMovingToParentViewController. This will return YES if the view controller is being shown because it was pushed, but NO if it is shown because another view controller was popped off the stack.
-(void)viewDidAppear:(BOOL)animated { //Code in view controller B
    [super viewDidAppear:animated];
    NSLog(@"isMovingToParentViewController: %d",self.isMovingToParentViewController);
    // this will log 1 if pushing from A but 0 if C is popped
}

A: EDIT :
Add UINavigationControllerDelegate in .h file

Also do this:
[self.yournavController setDelegate:self];

Method below is navigation controller delegate which is called when the navigation controller shows a new top view controller via a push, pop or setting of the view controller stack.
Add this method
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{

}

A: Hmm I think for that you need to track a global variable that knows either it is push from A or pop from C. What I would do is:

*

*Declare a BOOL variable isPush in appDelegate or some external .h file and synthesize it.

*When you are going from A to B i.e. it is a push, make it equal "YES" in A.
yourAppDelegate *myDelegate = (yourAppDelegate*) [[UIApplication SharedApplication] delegate];

myDelegate.isPush = YES;

Similarly before popping from C, make value of isPush = NO;

*

*In B's viewDidLoad, see the value of variable.

yourAppDelegate *myDelegate = (yourAppDelegate*) [[UIApplication SharedApplication] delegate];

if(myDelegate.isPush)
//means A was pushed

else
//means C was popped


text:
Q: How do I tell if the user has entered something other than Male, male, Female or female for my input? I am making a project and was wondering how I could use code to tell if the user has entered something other than "Male", "Female", "male", or "female".
I am using Python 3.0
This is my code:
 import time
def w(t):
  if t == t:
    time.sleep(t)
print("In the following story, you are a mouse. Please fill out the following information (the story will use this name and gender).")
w(3)
print('\n')
name = input("Your Name:")
w(0.5)
print('\n')
gender = input("Your Gender (Male / Female):")
w(0.5)
print('\n')
input("Press Enter to Begin The Story")
w(1)
print('\n')
print("The Lion and The Mouse")
print("A Short Tale by Aesop")
w(1)
print('\n')
print("Once upon a time in a secluded jungle, there was a mouse.")
w(2)
print('\n')
if gender == ("male" or "Male"):
    heorshe = "he"
    hisher = "his"
    himher = "him"
    himselfherself = "himself"
    HeShe = "He"
if gender == "female" or "Female":
    heorshe = "she"
    hisher = "her"
    himher = "her"
    himselfherself = "herself"
    HeShe = "He"

I would also like to be able to tell if the user has entered in nothing into the input! Please help!

A: You could just use else:, or if not 'male' or not 'Male:' and then print for example 'Please enter Male or Female.'


text:
Q: Azure Logic Apps (Standard) workflows getting deleted when I redeploy Logic App IaC part, how to avoid this? I set up a Logic App in IaC in the following way:
param environmentType string
param location string
param storageAccountSku string
param vnetIntegrationSubnetId string
param storageAccountTempEndpoint string
param ResourceGroupName string

/// Just a single minimum instance to start with and max scaling of 3 ///
var minimumElasticSize = 1
var maximumElasticSize = 3
var name = 'somename'
var logicAppName = 'logic-app-${name}-${environmentType}'

/// Storage account for service ///
resource logicAppStorage 'Microsoft.Storage/storageAccounts@2019-06-01' = {
  name: 'st4logicapp${name}${environmentType}'
  location: location
  kind: 'StorageV2'
  sku: {
    name: storageAccountSku
  }
  properties: {
    allowBlobPublicAccess: false
    accessTier: 'Hot'
    supportsHttpsTrafficOnly: true
    minimumTlsVersion: 'TLS1_2'
  }
}

/// Existing temp storage for extracting variables ///
resource storageAccountTemp 'Microsoft.Storage/storageAccounts@2021-08-01' existing = {
  scope: resourceGroup(ResourceGroupName)
  name: 'tmpst${environmentType}'
}

/// Dedicated app plan for the service ///
resource servicePlanLogicApp 'Microsoft.Web/serverfarms@2021-02-01' = {
  name: 'plan-${name}-logic-app-${environmentType}'
  location: location
  sku: {
    tier: 'WorkflowStandard'
    name: 'WS1'
  }
  properties: {
    targetWorkerCount: minimumElasticSize
    maximumElasticWorkerCount: maximumElasticSize
    elasticScaleEnabled: true
    isSpot: false
    zoneRedundant: ((environmentType == 'prd') ? true : false)
  }
}

// Create log analytics workspace
resource logAnalyticsWorkspacelogicApp 'Microsoft.OperationalInsights/workspaces@2021-06-01' = {
  name: '${name}-logicapp-loganalytics-workspace-${environmentType}'
  location: location
  properties: {
    sku: {
      name: 'PerGB2018' // Standard
    }
  }
}

/// Log analytics workspace insights ///
resource applicationInsightsLogicApp 'Microsoft.Insights/components@2020-02-02' = {
  name: 'application-insights-${name}-logic-${environmentType}'
  location: location
  kind: 'web'
  properties: {
    Application_Type: 'web'
    Flow_Type: 'Bluefield'
    publicNetworkAccessForIngestion: 'Enabled'
    publicNetworkAccessForQuery: 'Enabled'
    Request_Source: 'rest'
    RetentionInDays: 30
    WorkspaceResourceId: logAnalyticsWorkspacelogicApp.id
  }
}

// App service containing the workflow runtime ///
resource siteLogicApp 'Microsoft.Web/sites@2021-02-01' = {
  name: logicAppName
  location: location
  kind: 'functionapp,workflowapp'
  properties: {
    httpsOnly: true
    siteConfig: {
      appSettings: [
        {
          name: 'FUNCTIONS_EXTENSION_VERSION'
          value: '~3'
        }
        {
          name: 'FUNCTIONS_WORKER_RUNTIME'
          value: 'node'
        }
        {
          name: 'WEBSITE_NODE_DEFAULT_VERSION'
          value: '~12'
        }
        {
          name: 'AzureWebJobsStorage'
          value: 'DefaultEndpointsProtocol=https;AccountName=${logicAppStorage.name};AccountKey=${listKeys(logicAppStorage.id, '2019-06-01').keys[0].value};EndpointSuffix=core.windows.net'
        }
        {
          name: 'WEBSITE_CONTENTAZUREFILECONNECTIONSTRING'
          value: 'DefaultEndpointsProtocol=https;AccountName=${logicAppStorage.name};AccountKey=${listKeys(logicAppStorage.id, '2019-06-01').keys[0].value};EndpointSuffix=core.windows.net'
        }
        {
          name: 'WEBSITE_CONTENTSHARE'
          value: 'app-${toLower(name)}-logicservice-${toLower(environmentType)}a6e9'
        }
        {
          name: 'AzureFunctionsJobHost__extensionBundle__id'
          value: 'Microsoft.Azure.Functions.ExtensionBundle.Workflows'
        }
        {
          name: 'AzureFunctionsJobHost__extensionBundle__version'
          value: '[1.*, 2.0.0)'
        }
        {
          name: 'APP_KIND'
          value: 'workflowApp'
        }
        {
          name: 'APPINSIGHTS_INSTRUMENTATIONKEY'
          value: applicationInsightsLogicApp.properties.InstrumentationKey
        }
        {
          name: 'ApplicationInsightsAgent_EXTENSION_VERSION'
          value: '~2'
        }
        {
          name: 'APPLICATIONINSIGHTS_CONNECTION_STRING'
          value: applicationInsightsLogicApp.properties.ConnectionString
        }
        {
          name: 'AzureBlob_connectionString'
          value: 'DefaultEndpointsProtocol=https;AccountName=${storageAccountTemp.name};EndpointSuffix=${environment().suffixes.storage};AccountKey=${listKeys(storageAccountTemp.id, storageAccountTemp.apiVersion).keys[0].value}'
        }
        {
          name: 'azurequeues_connectionString'
          value: 'DefaultEndpointsProtocol=https;AccountName=${storageAccountTemp.name};EndpointSuffix=${environment().suffixes.storage};AccountKey=${listKeys(storageAccountTemp.id, storageAccountTemp.apiVersion).keys[0].value}'
        }
      ]
      use32BitWorkerProcess: true
    }
    serverFarmId: servicePlanLogicApp.id
    clientAffinityEnabled: false
  }

  /// VNET integration so flows can access storage and queue accounts ///
  resource vnetIntegration 'networkConfig' = {
    name: 'virtualNetwork'
    properties: {
      subnetResourceId: vnetIntegrationSubnetId
      swiftSupported: true
    }
  }
}

This all goes well and the Standard Logic App gets deployed.
Next, I define some workflows via azure pipelines (via zipdeploy) with code:
trigger:
  branches:
    include:
      - '*'

pool:
  name: "Ubuntu hosted"

stages:
- stage: logicAppBuild
  displayName: 'Logic App Build'
  jobs:
  - job: logic_app_build
    displayName: 'Build and publish logic app'
    steps:

    - task: CopyFiles@2
      displayName: 'Create project folder'
      inputs:
        SourceFolder: '$(System.DefaultWorkingDirectory)/logicapp'
        Contents: |
          **
        TargetFolder: 'project_output'

    - task: ArchiveFiles@2
      displayName: 'Create project zip'
      inputs:
        rootFolderOrFile: '$(System.DefaultWorkingDirectory)/project_output'
        includeRootFolder: false
        archiveType: 'zip'
        archiveFile: '$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip'
        replaceExistingArchive: true

    - task: PublishPipelineArtifact@1
      displayName: 'Publish project zip artifact'
      inputs:
        targetPath: '$(Build.ArtifactStagingDirectory)'
        artifactName: 'artifectdev'
        publishLocation: 'pipeline'

- stage: logicAppDeploy
  displayName: 'Logic app deployment'
  jobs:
  - job: logicAppDeploy
    displayName: 'Deploy the Logic apps'
    steps:
    - task: DownloadPipelineArtifact@2
      inputs:
        buildType: 'current'
        artifactName: 'artifectdev'
        targetPath: '$(Build.ArtifactStagingDirectory)'

    - task: AzureFunctionApp@1 # Add this at the end of your file
      inputs:
        azureSubscription: SC-DEV
        appType: functionApp # default is functionApp
        appName: logic-app-name-dev
        package: $(Build.ArtifactStagingDirectory)/**/*.zip

Running the IaC code first in a pipeline (called in a main.bicep with some other infra code)  results in successful deployment of the LogicApp. After then running the pipeline with the zip-deploy, the flows defined in the logicapp directory get deployed well, connections and all.
However, when the IaC pipeline is run again, all my defined workflows that were deployed with the zip-deploy in the second pipeline, are now gone. Even if I don't change anything in the IaC code.
Is there any way to circumvent this? It is totally unworkable for me to have this happen every time I deploy IaC code (for instance when adding some app setting).

A: Sharing the resolution as discussed here if someone looking for the similar issue.
For the zip deploy you need to use the AzureFunctionApp task with workflowapp apptype
task: AzureFunctionApp@1
displayName: Deploy Logic App Workflows
inputs:
azureSubscription: ${<!-- -->{variables.azureSubscription}}
appName: $(pv_logicAppName)
appType: 'workflowapp'
package: '$(Pipeline.Workspace)/LogicApps/$(Build.BuildNumber).zip'
deploymentMethod: 'zipDeploy'


text:
Q: multiple looped values in ajax call and controller function I'm having an issue in laravel with sending multiple input options (built by a foreach loop) into an ajax call so that I could send multiple values and loop them in the ajax call in order to properly send them to the controller. I need to call a stored procedure for each set of attributes so that if they choose 3 options, the ajax call would send them all and I would call the stored procedure 3 times for those values.
The blade:
@foreach($getRuleAttributes as $attributes)

        <input type="checkbox">
        {{ $attributes->title }}
        <input type="text" class="attribute_data">
        <input type="hidden" class="attribute_id" value="{{ $attributes->attributet_id }}">
        <input type="hidden" class="attribute_type" value="promo_codes">

@endforeach

This gives one input and then multiple options with checkboxes where multiple can be selected
ajax portion of blade:
 $("#savePromoCode").click(function(e){
    e.preventDefault();

    /********************************/
    /*This is where the issue starts*/
        var attr_title
        var attr_type_name
        var attr_value
    /*******************************/

    $.ajax({
       type:'POST',
       url:'postData',
       data:{rule_name:rule_name, attr_title:attr_title, attr_type_name:attr_type_name, attr_value:attr_value},
        _token: '{{ csrf_token() }}'
    });
});

Controller.php
public function postContent(Request $request)
    {
        $attr_title = $request->attr_title;
        $attr_type_name = $request->attr_type_name;
        $attr_value = $request->attr_value;

        $callProcedure = new procedureService();
        $ruleSave = $callProcedure->saveFunction($attr_title,$attr_type_name,$attr_value);
    }

My main question here, is if I have multiple attr_title, attr_type_name and attr_value then how exactly would I reconcile this in my ajax call and the controller? The variables are built by a php foreach, so if they select 3 of these then I would need the ajax call to send all three and the controller would call the stored procedure 3 times in order to get them all inserted.
How exactly would I do this?

A: You neen to send an array of values instead of sending it row by row.
try to compile your data into one array
$("#savePromoCode").click(function(e){
    e.preventDefault();

    /********************************/
    /*This is where the issue starts*/
        var attributes = [];
           ... //foreach there
        var item = {
          title = YOUR_TITLE,
          type_name = YOUR_TYPE_NAME,
          value = YOUR_TYPE_VALUE
        };
        attributes[] = item;
    /*******************************/

    $.ajax({
       type:'POST',
       url:'postData',
       data:{rule_name:rule_name, attributes:attributes},
        _token: '{{ csrf_token() }}'
    });
});

And then in your controller
$callProcedure = new procedureService();

foreach ($request->input('attributes') as $attribute){
    $callProcedure->saveFunction(
        $attribute['title'],
        $attribute['type_name'],
        $attribute['value']
    );
}

A: change name attr to array []. form will be like
<form id="form">
<?php $i = 1; ?>
@foreach($getRuleAttributes as $attributes)

        <input type="checkbox" name="attribute[{{$i}}]['checked']">
        <input type="text" name="attribute[{{$i}}]['attribute_title']" value="{{ $attributes->title }}">
        <input type="text" name="attribute[{{$i}}]['attributet_id']" value="{{ $attributes->attributet_id }}">
        <input type="text" name="attribute[{{$i}}]['attribute_type']" value="attribute_type1">

<?php $i++; ?>
@endforeach

<input type="submit" value="submit" id="savePromoCode">

jQuery code

In controller using parse_str get the serialize value in array.
 public function postContent(Request $request){
    $form_data = $request->form_data;
    parse_str($form_data, $my_array_of_vars);
    $attr = $my_array_of_vars['attribute'];

    /*echo "
";
    print_r($attr);*/

    foreach($attr as $key=>$value){

        //get the value of checked row - attribute_title, attributet_id, attribute_type, Confirm what attr you need use that one
        if(isset($value["'checked'"]) && $value["'checked'"] != ''){
            echo $attribute_title = $value["'attribute_title'"];
            echo $attributet_id1 = $value["'attributet_id'"];
            echo $attribute_type1 = $value["'attribute_type'"];
            $callProcedure = new procedureService();
        }
    }
}


text:
Q: How to add custom layout in preference activity?
Possible Duplicate:
How to add a button to PreferenceScreen

I want to add custom view at the bottom of the preference activity and also want to implement onClick of the views added in the screen? When i try to add view using layout inflator in preference screen it is always place at top of the preference view. But I want to show my view at bottom of the preference screen.
Below is the code snippets for adding layout in preference activity.
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.bottom_preference, null, true);
RelativeLayout.LayoutParams rl=new RelativeLayout.LayoutParams(android.widget.RelativeLayout.LayoutParams.MATCH_PARENT,android.widget.RelativeLayout.LayoutParams.MATCH_PARENT);
rl.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
addContentView(view,rl);

A: try this:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    RelativeLayout parent = new RelativeLayout(this);

    Button button = new Button(this);
    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) generateLayoutParams(null);
    params.setMargins(35, 35, 0, 0);
    params.addRule(RelativeLayout.ALIGN_BOTTOM);
    button.setLayoutParams(params);

    parent.addView(button);

    setContentView(rl);
}


text:
Q: Cast error by printing the elements of a string in a pointer array in C
First: I'm a beginner with pointers.

I just want to print the chars of the strings in the pointer Array. It works fine, but I get two Problems in Eclipse Juno (Mac OS X):

1. assignment makes pointer from integer without a cast

2. format '%c' expects type 'int', but argument 2 has type 'char *'
#include<stdio.h>
#include<string.h>

int main(void)
{
    char *words[] = {"word1", "word2", "word3", "word4", "word5"};
    char *tempWord,*tempChar;
    int i, j, numElems2;

    int numElems = sizeof words / sizeof words[0];
    for(i = 0; i < numElems; ++i)
    {
        tempWord = words[i];
        numElems2 = strlen(tempWord);

        for(j = 0; j < numElems2; ++j)
        {
            tempChar = tempWord[j];
            printf("%c", tempChar);
        }
        printf("\n");
    }

    return 0;
}

I understand the first problem, but don't know how to solve it. The second problem I don't understand. What has a 'char' to do with 'int'?
Maybe there is somebody who can give me some advice.
Thanks.

A: tempChar needs to be a char, not a char * as you currently have it.
Both of your warning messages tell you this.

A: I'm not sure, what this code should to do, but, firstly tempChar must be type char not *char, if you want to print string with printf, you need to use "%s"...


text:
Q: Is it possible to use MediaWiki Math extension for Semantic Media Wiki annotations? We are building a knowledge base storing a lot of formulas. For presentation purposes, all our formulas are displayed inside a <math>...</math> pair of tags.
We recently enabled SMW extension, with the intent to store all the formulas as semantic annotations.
Sadly, we cannot find a way to enter such an annotation within the math tags.
Is there a way to achieve the desired results ?
i.e., storing formulas as SMW annotations, and having them rendered as Latex formula each time they are presented.

A: Generally, the content of XML-style tags (<foo>...</foo>) is interpreted literally, while the content of template-style functions ({{#foo:...}}) is interpreted as wikimarkup and property lookups or other semantic syntax will work. There is a special function #tag to convert the first type to the second. So you can probably use something like {{#tag:math|{{#show|SomeFormula|?formula}} }}.

A: To complete Tgr answer:
In order for the formula to actually show up, one should make sure that the formula property does not have the default Pagetype. Assigning it the Texttype works very well (perhaps other types would work as well).
To do that, go to the Properties:Formula special page on the wiki, and create it with the content:
[[Has type::Text]]


text:
Q: Android animation only when ListView scrolls down I have a ListView in a layout,
I need to apply animation (appearing from bottom to top) only when list is scrolled down.
How can I do it?
Please help me.

A: Hope this will help you out.
Google plus animation
up_from_bottom.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="@android:anim/decelerate_interpolator">
    <translate
        android:fromXDelta="0%" android:toXDelta="0%"
        android:fromYDelta="100%" android:toYDelta="0%"
        android:duration="400" />
</set>

down_from_top.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="@android:anim/decelerate_interpolator">
    <translate
        android:fromXDelta="0%" android:toXDelta="0%"
        android:fromYDelta="-100%" android:toYDelta="0%"
        android:duration="400" />
</set>

Code:
private int lastPosition = -1;

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    //Load your view, populate it, etc...
    View view = ...;

    Animation animation = AnimationUtils.loadAnimation(getContext(), (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
    view.startAnimation(animation);
    lastPosition = position;

    return view;
}

A: add animation to specific view (could be ImageView , LinearLayout ...) , animation will start when getView method called mean when adapter inflate any new item
 @Override
      public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
        TextView textView = (TextView) rowView.findViewById(R.id.label);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
        setAnimation(YOUR_VIEW, position);
    }

 private void setAnimation(View viewToAnimate, int position)
    {
        // If the bound view wasn't previously displayed on screen, it's animated
        if (position > lastPosition) // you can put any rule you need
        {
            Animation animation = AnimationUtils.loadAnimation(_Context, R.anim.push_left_in); // add any animation you want
            viewToAnimate.startAnimation(animation);
            lastPosition = position;
        }
    }


text:
Q: Disable required auth for action A developer made for me a website where you can vote for things only if you are logged in. At first, when we launched the website it was not a requirement and I would like to go back to that.
I found a file - Voting.php:
class Voting
{
    public function getKey()
    {
        if (auth()->check()) {
            return auth()->user()->id;
        } else {
            return request()->ip();
        }
    }
    public function getVotes($key)
    {
        $int = config('app.settings.vote_interval');
        $votes = Cache::get('votes::' . $key);
        if ($votes) {
            $now = time();
            foreach ($votes as $key => $value) {
                if ($value < $now - $int) {
                    unset($votes[$key]);
                }
            }
        } else {
            $votes = [];
        }
        return $votes;
    }
}

Am I looking into the right file?
Can I get some help to disable the required auth for voting?
Thank you!

A: From the limited information you provided. I am not sure how much this would help. Having said that, here is my attempt to help.
class Voting
{
    public function getKey()
    {
        return request()->ip();
    }

    public function getVotes($key)
    {
        $int = config('app.settings.vote_interval');
        $votes = Cache::get('votes::' . $key);
        if ($votes) {
            $now = time();
            foreach ($votes as $key => $value) {
                if ($value < $now - $int) {
                    unset($votes[$key]);
                }
            }
        } else {
            $votes = [];
        }
        return $votes;
    }
}


text:
Q: How the codes work for loading image from Gallery Android I have the codes work for loading images from the gallery but I really do not understand how it works. Here are the codes.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { //Browse Gallery is requested

            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            loadImage(picturePath);         //load picture according the path
            image_View.setImageBitmap(pic); //Show the selected picture
        }
    }

Uri selectedImage = data.getData();

Get the uri of selected image from intent
String[] filePathColumn = { MediaStore.Images.Media.DATA };

MediaStore.Images.Media.DATA is constant. I do not understand why do not use String instead of String[]
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);

I do not understand this line.
cursor.moveToFirst();

Move to the first picture in Gallery.
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

For this one, I always get 0 no matter which picture I choose.
String picturePath = cursor.getString(columnIndex);

Since columnIndex is always 0, then how can it get a different path for different pictures?
Can anyone help me to check whether my explanation is correct and explain the line that I do not understand? Thanks.

A: 1-
Uri selectedImage = data.getData();

This is the statement where you need to read the data passed through another intent which you called earlier via startActivityForResult method. In this case probably you open an intent and let the user select an image, then the URI of the image will be returned to you and you use getData to read that.
2-
String[] filePathColumn = { MediaStore.Images.Media.DATA };

When you want cursors to read something a Content Provider (via ContentResolver) you need to specify which columns you need to read from the database, and the argument you need to pass should be an array of String (whether it has one or more columns you still need to pass an array). MediaStore.Images.Media is a Database Contract which contains constants which you need to use to talk to Content Providers
3-
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);

Cursors are used for reading data from Content Providers. If you are familiar with other programming languages it is like reading rows from database and your results are stored in Cursors. When you pass URI, you don't need to specify which database to read, ContentResolver will find that out for you (this is an advantage of using content providers)
4-
cursor.moveToFirst();

When you read the desired rows from the database (in this case probably you just selected one image), you need to move the cursor to point to the first entry (row) of the returned results
5-
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

You need to know which column you need to access to read your desired data (in this case file path name). so you ask cursor what is the column index of the file pathname and it will return you the column index. and of course in this case it will be always 0 because you only asked the content provider to return one column (file pathname) so there would be no more data to show other than that
6-
String picturePath = cursor.getString(columnIndex);

and finally this statement asks cursor to get the file pathname located at the index (in this case index 0) so at the end you have your path to file. Note that you can read only one picture data at a time with this method

A: Cursors store query result records in rows and grant many methods to access and iterate through the records. Also int columnIndex = cursor.getColumnIndex(filePathColumn[0]); is the reason why you always get 0 for your index


text:
Q: Typescript can infer recursive function, but not recursive type Typescript seems to be able to infer the type of a recursive function:
/**
 * Typescript correctly infers the type is
 *
 * const referencesSelf: () => ...
 *
 * Where the ellipsis means recursion of the function
 */
const referencesSelf = () => {
  return referencesSelf;
};

However, unable to infer a class with a recursive nature:
class ReferencesSelf {
  _self: () => ReferencesSelf;

  constructor(gen: () => ReferencesSelf) {
    this._self = gen;
  }
}

/**
 * Typescript warns with:
 *
 * `foo' implicitly has type 'any' because it does not have a type annotation and is
 * referenced directly or indirectly in its own initializer.ts(7022)
 */
const foo = new ReferencesSelf(() => {
  return foo;
});

Two questions:

*

*Why? Is this behavior documented somewhere? I couldn't find any callouts of this.

*Is there a way to get TS to infer the recursive function type without defaulting to nil?

On Typescript 4.3.2.

A: For the second part of your question use as keyword like that:
const foo = new ReferencesSelf(() => {return foo;}) as ReferencesSelf;

PlaygroundLink
Also see below links. Maybe it can help for first part.
Are circular references supported when using class expressions?
'Class' is referenced directly or indirectly in its own type annotation


text:
Q: publishing to svn from perforce? I have two projects which I manage internally using Perforce.  These are also published to google code using svn.

http://code.google.com/p/orapig/
http://code.google.com/p/cx-oracle-demos/

I currently have a set of scripts that copy from the perforce area in my home directory to the svn area, sync it, diff it, and commit it.
It seems that I might be able to just do a svn checkout in the perforce-managed area and perform the svn operations in place.
Has anybody done something like that?  Any hints, pointers, etc.?

A: I don't see why not, if you can make perforce ignore the .svn directories, then a SVN WC is just an ordinary directory of files.
You can make your changes to those files, and commit them as normal using SVN - SVN simply uses the .svn dirs to detect whether anything has changed and to generate the diffs to send to the repository. Perforce won't affect any part of that - as long as you can make it ignore the .svn dirs.


text:
Q: How to use split function in intersection to compare two text files I have two text files that i'd like to compare and have any similaritie listed in a new file. For example, if one file contains "123:example:example" and another file contains "123" and "example", i would want "123" and "example" to count as the same and to be listed in a new file. I think that I need to use a split function to have it split at the colon, but I am unsure where I can put that. I tried putting it where the splitlines() is, but that gives an error saying an integer is needed. I am very new to python so any advice or hints are appreciated!
This currently works, but only for lines without colons.
#choose the two files to open
#read the two files, intersection method returns set that
contains similarity
file1 = set(open('file1.txt').read().lower().splitlines())
file2 = set(open('file2.txt').read().lower().splitlines())

same = file1.intersection(file2)

#any matches are listed in a new file
with open('result.txt', 'a') as new_file:
for line in same:
    new_file.write(line + '\n')

More complete example:
**File 1:**
123:example:test
testing
abc

**file2:**
test
456:testing
ABC

**desired output in new file:**
test
testing
abc

A: Split each line and then put each element of that into the set, using a multi-level list comprehension.
file1 = set([item for line in open('file1.txt').read().lower().splitlines() for item in line.split(':')])
file2 = set([item for line in open('file2.txt').read().lower().splitlines() for item in line.split(':')])

same = file1.intersection(file2)


text:
Q: Code::Blocks não imprime o valor do ponteiro Desenvolvi um código em C com o objetivo de imprimir o valor e o endereço da variável x utilizando um ponteiro p, mas o Code::Blocks não imprime os valores.
    #include <stdio.h>
    #include <conio.h>

    int main()
    {
    int x=2;
    int *p;
    p = &x;

    printf("O valor de X e: %p\n", *p);

    printf("O valor de X e: %d\n", p);

    return(0);

    }

A: Não use conio.h, ainda que neste caso nem precise. E se estiver uma IDE com compilador ruim (Dev-C++), pare de fazer isto. Alias o Code::Blocks não faz nada na execução do código mesmo, entenda quem é quem na programação.
Pelo que entendi o primeiro você quer imprimir o endereço da memória onde está o X já que usou %p, e o segundo quer imprimir o valor de X. Então tem que arrumar o texto para dar uma informação correta.
Aí um problema é que está invertido. p já é um endereço de memória, então é só usá-lo no primeiro. O segundo quer o valor e pegá-lo indiretamente pela variável p que é um endereço, então agora tem que fazer a operação inversa que tinha feito para pegar o endereço de X, então tem que fazer o que se chama derreferenciar, que é feito com o operador *. O *P quer dizer "pegue o valor que está no endereço de p".
Coloquei um (void *) porque bons compiladores com a configuração correta impede a compilação direta, eles te obrigam ser explícito no que está usando para indicar que não está confundindo o que está mandando. Mas é possível não usar em certas circunstâncias (não usei no Coding Ground, olhe lá), sob risco de fazer algo errado em código real mais complexo.
#include <stdio.h>

int main() {
    int x = 2;
    int *p = &x;
    printf("O endereço de X e: %p\n", (void *)p);
    printf("O valor de X e: %d\n", *p);
}

Veja funcionando no ideone. E no repl.itd. Também coloquei no GitHub para referência futura.
Veja mais em Qual o significado do operador "&" (e comercial) na linguagem C? e Operador & e * nas funções.

A: int x=5;
int *p;
p = &x;
printf("O valor de X e: %d\n", *p);
printf("O valor de X e: %d\n", p);

O primeiro printf() imprime o valor de x, o segundo imprime o endereço do apontador.
Todo o seu codigo está bem, esse 'c' é 12 em hexadecimal.


text:
Q: C++ Primer Mistake in counting I've got some problem with 7th exercise of 6th chapter from C++ Primer Plus book. Well, I think I made this exercise well, but my compiler think otherwise. The program should count number of vowels, consonants and other characters that start the word. The problem is that it counts vowels instead of consonants and consonants instead of vowels.
For example: if I enter "a e o i u" it says that I entered 5 words started by consonants.
Thanks in advance for explanation.
Here is the code:
#include <iostream>
#include <cstring>

char word[20];

int others=0;
int vowels=0;
int consonants=0;

int main()
{
    std::cout<<"Enter words (q to quit):";
    std::cin>>word;

    while(strcmp(word,"q"))
    {
        word[0]=tolower(word[0]);
        if(!isalpha(word[0]))
            others++;
        else if(word[0]!='a'&&word[0]!='e'&&word[0]!='i'&&word[0]!='o'&&word[0]!='u')
            consonants++;
        else vowels++;

        std::cin>>word;
    }
    std::cout<<vowels<<" words beginning with vowels\n";
    std::cout<<consonants<<" words beginning with consonants\n";
    std::cout<<others<<" others";

    return 0;
}

A: The reason here is when you type a e i o u 'they' fed in to std::cin as 5 different words. Because, cin in this situation takes space as the word separator, you will be prompted to enter new words after 5 iterations. So it's correct. If you enter a e i o u q then you will not be prompted again to enter any input since 6th word is q which is supposed to exit from your loop. So the behaviour is correct.
If you debug the program you can understand what's really going on.


text:
Q: Angular 2 iframe confusion I am attempting to change the value of an element inside of an iframe in Angular 2. I have tried many things, but am continuously unable to reference an item using getElementById(). I have a test scenario which works in one case, and not another, which is serving to confuse me even further:
component.html

test.html

Wow

working typescript (prints
Wow
)
export class MyComponent implements AfterViewInit {

    @ViewChild('iframe') iframe: ElementRef;

    ngAfterViewInit() {
        var doc = this.iframe.nativeElement.contentDocument;
        doc.open();
        doc.write('
Wow
');
        doc.close();
        console.log(doc.getElementById("wow"));
    }
}

non-working typescript (prints null)
export class MyComponent implements AfterViewInit {

    @ViewChild('iframe') iframe: ElementRef;

    ngAfterViewInit() {
        var doc = this.iframe.nativeElement.contentDocument;
        console.log(doc.getElementById("wow"));
    }
}

Question
How in the world can I get the second one to properly print the element? No matter what I do or what I put in test.html, it is always null.

A: Inside ngAfterViewInit(), it's likely that test.html hasn't been loaded into iframe yet.
This can be subverted using the (load)="yourLoadFunction()" directive on your iframe like
If you then move the code from ngAfterViewInit() into yourLoadFunction(), it should work correctly.


text:
Q: Optimizing a "stop light" circuit to run on lower voltage I am specifically talking about the circuit found here.

I want to make this same circuit but make it run on much lower voltage, preferably a coin cell or two. Longevity is not important.

A: You could run it from 6 volts - just stick two CR2032 coin cells together. Make sure your 4017 and 555 ICs are the CMOS versions, as they can run on lower voltages (see your data sheets). You also may want to reduce the value of the 470 ohm current-limiting resistors that are before the LEDs, perhaps 330 ohm if you're on 6 volts.
That looks like fun, I'm going to build it myself tonight. Thanks!


text:
Q: Longest Common Prefix string Below is my recursive approach to finding the longest common prefix to a set of strings.

package recursion;
public class LongestCommonPrefix {
    public static String longestCommonPrefix(String[] str) {
        String finalStr = longestCommonPrefixHelper(str,"");
        return finalStr;
    }
    public static String longestCommonPrefixHelper(String[] str,String prefix) {
        if(str.length==0) {
            return prefix;
        }
        System.out.println("Prefix is "+prefix);
        for(int i=0;i<str.length;i++) {
            if(str[i].equals("")) {
                return prefix;
            }
        }
        String ch = str[0].substring(0, 1);
        for(int i=0;i<str.length;i++) {
            if(!str[i].substring(0, 1).equals(ch)) {

                return prefix;
            }
            else if(str[i].length()>1)
                str[i] = str[i].substring(1, str[i].length());
            else
                str[i]="";
        }
        prefix= prefix+ch;
        longestCommonPrefixHelper(str, prefix);
        return prefix;
    }

    public static void display(String[] s) {
        for(int i=0;i<s.length;i++) {
            System.out.print(s[i]+" ");
        }
    }

    public static void main(String[] args) {
        String[] s = {"Sujit","Suhail","Suit","Susan"};

        System.out.println(longestCommonPrefix(s));
    }
}

For some reason, I do not get the correct output.  There happens to be a minor thing which I have missed. Any form of help is much appreciated. Thanks in advance

A: change this
prefix= prefix+ch;
longestCommonPrefixHelper(str, prefix);
return prefix;

to
return longestCommonPrefixHelper(str, prefix+ch);

you forget to call the recursion
  public class LongestCommonPrefix {
        public static String longestCommonPrefix(String[] str) {
            String finalStr = longestCommonPrefixHelper(str,"");
            return finalStr;
        }
        public static String longestCommonPrefixHelper(String[] str,String prefix) {
            if(str.length==0) {
                return prefix;
            }

            for(int i=0;i<str.length;i++) {
                if(str[i].equals("")) {
                    return prefix;
                }
            }

            String ch = str[0].substring(0, 1);
            for(int i=0;i<str.length;i++) {
                if(!str[i].substring(0, 1).equals(ch)) {
                    return prefix;
                }
                else if(str[i].length()>1)
                    str[i] = str[i].substring(1, str[i].length());
                else
                    str[i]="";
            }

            return longestCommonPrefixHelper(str, prefix+ch);
        }

        public static void display(String[] s) {
            for(int i=0;i<s.length;i++) {
                System.out.print(s[i]+" ");
            }
        }

        public static void main(String[] args) {
            String[] s = {"Sujit","Suhail","Suit","Susan"};

            System.out.println(longestCommonPrefix(s));
        }
    }